using System;
using System.Web.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using IWCommunity.Common;

namespace IWCommunity.UserRoleManagement
{
    /// <summary>
    /// Code behind for UserDelete.aspx
    /// </summary>
    public class UserDelete : LayoutsPageBase
    {
        protected Label deleteMsg;

        protected override bool RequireSiteAdministrator
        {
            get { return true; }
        }

        protected override void OnLoad(EventArgs e)
        {
            this.CheckRights();
        
            // display error confirmation message
            string userName = Request.QueryString["USERNAME"];
            if (!string.IsNullOrEmpty(userName))
                deleteMsg.Text = "Confirm that you want to delete the user '" + Request.QueryString["USERNAME"] + "'";
            else
                SPUtility.TransferToErrorPage("User Not Found");
        }

        protected void OnDelete(object sender, EventArgs e)
        {
            string userName = Request.QueryString["USERNAME"];

            try
            {
                // delete user from FBA data store
                Membership.DeleteUser(userName);

                System.Web.Profile.ProfileManager.DeleteProfile(userName); //delete user profile

                // delete user from SharePoint            
                SPIisSettings settings = Utilities.GetFBAIisSettings(this.Site);
                //see if the user is a valid site user, if so then delete user from siteusers too
                SPUser user = this.Web.SiteUsers[settings.MembershipProvider + ":" + userName];
                                      
                if (user != null)
                {
                    this.Web.SiteUsers.Remove(settings.MembershipProvider + ":" + userName);
                    this.Web.Update();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToLower() != "user cannot be found.") //if user is not in site collectio
                    Logger.LogError(ex, true);                
            }
                        
            Response.Redirect("UsersDisp.aspx");
        }

    }
}
